/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ytmc.uploader;

import com.google.gdata.client.GoogleService.CaptchaRequiredException;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.util.AuthenticationException;

/**
 *
 * @author K
 */
public class Authentication
{
    private YouTubeService service;
    private Credentials authCredentials;

    public void Authenticate(Credentials credentials) throws CaptchaRequiredException, AuthenticationException
    {
        if(authCredentials != null && authCredentials.equals(credentials))
        {
            return;
        }

        try
        {
            service.setUserCredentials(credentials.getLogin(), credentials.getPassword());
            authCredentials = credentials;
        }
        catch (CaptchaRequiredException ex)
        {
            String url = ex.getCaptchaUrl();
            String newUrl = "https://www.google.com/accounts/" + url.substring(url.indexOf("Captcha", 0));
            throw new CaptchaRequiredException("Do zalogowania wymagane jest rozwiazanie CAPTCHA", newUrl, ex.getCaptchaToken());
        }
        catch (AuthenticationException ex)
        {
            throw new AuthenticationException("Niepoprawna nazwa użytkownika lub hasło do serwisu YouTube.");
        }
    }

    public void Authenticate(Credentials credentials, String captchaToken, String captchaAnswer) throws CaptchaRequiredException, AuthenticationException
    {
        if(authCredentials != null && authCredentials.equals(credentials))
        {
            return;
        }

        try
        {
            service.setUserCredentials(credentials.getLogin(), credentials.getPassword(), captchaToken, captchaAnswer);
            authCredentials = credentials;
        }
        catch (CaptchaRequiredException ex)
        {
            String url = ex.getCaptchaUrl();
            String newUrl = "https://www.google.com/accounts/" + url.substring(url.indexOf("Captcha", 0));
            throw new CaptchaRequiredException("Do zalogowania wymagane jest rozwiazanie CAPTCHA", newUrl, ex.getCaptchaToken());
        }
        catch (AuthenticationException ex)
        {
            throw new AuthenticationException("Niepoprawna nazwa użytkownika lub hasło do serwisu YouTube.");
        }
    }
  
    public Authentication(YouTubeService service)
    {
        this.service = service;
    }
}
